//
//  RSChooseTimePickerView.m
//  RSChooseTimeCase
//
//  Created by thinkjoy on 16/9/9.
//  Copyright © 2016年 Thinkjoy_RS. All rights reserved.
//

#import "RSChooseTimePickerView.h"


#define kWinH [[UIScreen mainScreen] bounds].size.height
#define kWinW [[UIScreen mainScreen] bounds].size.width

//宽高比系数
#define WFACTOR (kWinW/320)
#define HFACTOR (kWinH/480)

#pragma mark - 日志开关
#ifdef DEBUG
#define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define DLog(...)
#endif

@interface RSChooseTimePickerView()<UIPickerViewDelegate,UIPickerViewDataSource>

@property(nonatomic,strong) UIView      * pickerViewCase;
@property(nonatomic,strong) UIButton    *bgButton;
@property   (nonatomic,strong)  UIPickerView    *   pickerView;

//存放  年  月 日 时 分 的数组
@property   (nonatomic,strong)  NSMutableArray * yearMuAry;
@property   (nonatomic,strong)  NSArray * monthAry;
@property   (nonatomic,strong)  NSArray * hourAry;
@property   (nonatomic,strong)  NSArray * minuAry;
@property   (nonatomic,strong)  NSMutableArray * dayMuAry;


//当前的时间
@property   (nonatomic,assign)  NSInteger    nowYear;
@property   (nonatomic,assign)  NSInteger    nowMonth;
@property   (nonatomic,assign)  NSInteger    nowDay;
@property   (nonatomic,assign)  NSInteger    nowHour;
@property   (nonatomic,assign)  NSInteger    nowMinu;


@property   (nonatomic,assign)  NSInteger   yearRow;
@property   (nonatomic,assign)  NSInteger   monthRow;
@property   (nonatomic,assign)  NSInteger   dayRow;
@property   (nonatomic,assign)  NSInteger   hourRow;

@property   (nonatomic,copy)    NSString    * chooseTimeStr;

@end

//当前行
//static  NSInteger   hourRow;

@implementation RSChooseTimePickerView

- (id)init
{
    self    =   [super init];
    if (self) {
        self.frame  =   CGRectMake(0, 0, kWinW, kWinH);
        [[[UIApplication sharedApplication] keyWindow] addSubview:self];
        //半透明背景按钮
        _bgButton = [[UIButton alloc]init];
        [self addSubview:_bgButton];
        [_bgButton addTarget:self action:@selector(dismissDatePicker:) forControlEvents:UIControlEventTouchUpInside];
        _bgButton.tag   =   100;
        _bgButton.backgroundColor = [UIColor blackColor];
        _bgButton.alpha = 0.1;
        _bgButton.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        
        _pickerViewCase =   [[UIView alloc]initWithFrame:CGRectMake(20*WFACTOR, 90*WFACTOR, 280*WFACTOR, 160*WFACTOR)];
        [self    addSubview:_pickerViewCase];
        _pickerViewCase.backgroundColor =   [UIColor whiteColor];
        
        UILabel * titleLabel    =   [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.pickerViewCase.frame.size.width, self.pickerViewCase.frame.size.height*7.0/43.0)];
        titleLabel.backgroundColor  =   [UIColor whiteColor];
        titleLabel.text =   @"请选择时间";
        titleLabel.textAlignment    =   NSTextAlignmentCenter;
        titleLabel.textColor    =   [UIColor greenColor];
        [self.pickerViewCase    addSubview:titleLabel];
        
        UIButton    * commitButt    =   [UIButton buttonWithType:UIButtonTypeCustom];
        commitButt.frame    =   CGRectMake(0, self.pickerViewCase.frame.size.height*(1.0-8.0/43.0), self.pickerViewCase.frame.size.width, self.pickerViewCase.frame.size.height*8.0/43.0);
        [commitButt  setBackgroundColor:[UIColor greenColor]];
        [commitButt  setTitle:@"确定" forState:UIControlStateNormal];
        [commitButt  setTintColor:[UIColor whiteColor]];
        commitButt.tag  =   200;
        [self.pickerViewCase    addSubview:commitButt];
        [commitButt  addTarget:self action:@selector(dismissDatePicker:) forControlEvents:UIControlEventTouchUpInside];
        
        _pickerView    =   [[UIPickerView alloc]initWithFrame:CGRectMake(0, titleLabel.frame.size.height, self.pickerViewCase.frame.size.width, self.pickerViewCase.frame.size.height*28.0/43)];
        
        self.pickerView.delegate    =   self;
        self.pickerView.dataSource  =   self;
        
        [self    getNowTime];   //获得设备当时的时间
        [self    sourceAry];    //获得数据源
        
        [self.pickerView  selectRow:self.nowYear-2016 inComponent:0 animated:YES];
        [self.pickerView  selectRow:self.nowMonth-1 inComponent:1 animated:YES];
        [self.pickerView  selectRow:self.nowDay-1 inComponent:2 animated:YES];
        [self.pickerView  selectRow:self.nowHour*2 inComponent:3 animated:YES];
        
        //如果当前的分钟<30,显示为30; >30,显示00,把小时数加1
        if (self.nowMinu<30) {
            [self.pickerView  selectRow:self.nowHour*2+1 inComponent:3 animated:YES];
        }else{
            [self    mimuFullIntoDay];
        }
        
        [self.pickerViewCase    addSubview:self.pickerView];
        
        self.yearRow    =   [self.pickerView selectedRowInComponent:0];
        self.monthRow   =   [self.pickerView selectedRowInComponent:1];
        self.dayRow     =   [self.pickerView selectedRowInComponent:2];
        self.hourRow    =   [self.pickerView selectedRowInComponent:3];
        
        
        //弹框出现,退出键盘
        [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    }
    
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissDatePicker:) name:IWantCarVCDismiss object:nil];
    
    return self;
}
- (void)mimuFullIntoDay
{
    if ([self.pickerView selectedRowInComponent:3]+2>=self.hourAry.count*2) {
        [self.pickerView selectRow:0 inComponent:3 animated:YES];
        //        [self.pickerView selectRow:[self.pickerView selectedRowInComponent:2]+1 inComponent:2 animated:YES];
        [self dayFullIntoMonth];
    }else{
        [self.pickerView selectRow:[self.pickerView selectedRowInComponent:3]+2 inComponent:3 animated:YES];
    }
}
/**
 *  月满了就进位
 */
- (void)monthFullIntoYear
{
    if ([self.pickerView selectedRowInComponent:1]+1>=self.monthAry.count) {
        [self.pickerView selectRow:0 inComponent:1 animated:YES];
        [self.pickerView selectRow:[self.pickerView selectedRowInComponent:0]+1 inComponent:0 animated:YES];
    }else{
        [self.pickerView selectRow:[self.pickerView selectedRowInComponent:1]+1 inComponent:1 animated:YES];
    }
}
- (void)dayFullIntoMonth
{
    if ([self.pickerView selectedRowInComponent:2]+1>=[self getDaysWithYearAndMonth]) {
        [self.pickerView selectRow:0 inComponent:2 animated:YES];
        //        [self.pickerView selectRow:[self.pickerView selectedRowInComponent:1]+1 inComponent:1 animated:YES];
        [self    monthFullIntoYear];
    }else{
        [self.pickerView selectRow:[self.pickerView selectedRowInComponent:2]+1 inComponent:2 animated:YES];
    }
}


/*
 -(id)initWithFrame:(CGRect)frame
 {
 self    =   [super initWithFrame:frame];
 if (self) {
 self.backgroundColor    =   [UIColor whiteColor];
 
 UILabel * titleLabel    =   [[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height*7.0/43)];
 titleLabel.text =   @"请选择时间";
 titleLabel.backgroundColor  =  [UIColor lightGrayColor];
 titleLabel.textAlignment    =   NSTextAlignmentCenter;
 [self    addSubview:titleLabel];
 titleLabel.textColor        =   [UIColor greenColor];
 
 UIButton    * commitButt    =   [UIButton buttonWithType:UIButtonTypeCustom];
 commitButt.frame    =   CGRectMake(0, self.frame.size.height*(1.0-8.0/43.0), self.frame.size.width, self.frame.size.height*8.0/43.0);
 [commitButt  setBackgroundColor:[UIColor greenColor]];
 [commitButt  setTitle:@"确定" forState:UIControlStateNormal];
 [commitButt  setTintColor:[UIColor whiteColor]];
 [self    addSubview:commitButt];
 [commitButt  addTarget:self action:@selector(clickCommitButt:) forControlEvents:UIControlEventTouchUpInside];
 
 _pickerView    =   [[UIPickerView alloc]initWithFrame:CGRectMake(0, titleLabel.frame.size.height, self.frame.size.width, self.frame.size.height*28.0/43)];
 
 self.pickerView.delegate    =   self;
 self.pickerView.dataSource  =   self;
 
 [self    sourceAry];
 [self    getNowTime];
 
 [self.pickerView  selectRow:self.nowMonth-1 inComponent:0 animated:YES];
 [self.pickerView  selectRow:self.nowDay-1 inComponent:1 animated:YES];
 [self.pickerView  selectRow:self.nowHour*2 inComponent:2 animated:YES];
 if (self.nowMinu<30) {
 [self.pickerView  selectRow:self.nowHour*2+1 inComponent:2 animated:YES];
 }else{
 [self.pickerView  selectRow:self.nowHour*2+2 inComponent:2 animated:YES];
 }
 [self    addSubview:self.pickerView];
 
 }
 return self;
 }*/

#pragma mark    UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 4;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return self.yearMuAry.count;
            break;
        case 1:
            return self.monthAry.count;
            break;
            
            //      一月有几天需要判断年和月两个参数
        case 2:
        {
            return [self getDaysWithYearAndMonth];
        }
            break;
        case 3:
        {
            return 48;
        }
            break;
        default:
            break;
    }
    return 0;
}

#pragma mark UIPickerViewDelegate
//设置列高
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    if (component ==0) {
        return pickerView.frame.size.height/4.0;//第一组键(列)的高度
    }else{
        return pickerView.frame.size.height/4.0;//第二组键(列)的高度
    }
}

//返回每列的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return pickerView.frame.size.width/3.0;//第一组键(列)的宽度
            break;
        case 1:
            return pickerView.frame.size.width/6.0;//第2组键(列)的宽度
            break;
        case 2:
            return pickerView.frame.size.width/6.0;//第2组键(列)的宽度
            break;
        case 3:
            return pickerView.frame.size.width/3.0;//第2组键(列)的宽度
            break;
        default:
            break;
    }
    return 0;
}

//给行赋值
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return self.yearMuAry[row];
            break;
        case 1:
            return self.monthAry[row];
            break;
            
            //      一月有几天需要判断年和月两个参数
        case 2:
        {
            return [NSString stringWithFormat:@"%ld",(long)row+1];
        }
            break;
        case 3:
        {
            NSString    * str = [NSString stringWithFormat:@"%@:%@",self.hourAry[row/2],self.minuAry[row%2]];
            return str;
        }
            break;
        default:
            break;
    }
    return 0;
}


//被选中的第几列 的 第几行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component) {
        case 0:
        {
            NSInteger   row1    =   [pickerView selectedRowInComponent:1];  //月
            NSInteger   row2    =   [pickerView selectedRowInComponent:2];  //天
            NSInteger   row3    =   [pickerView selectedRowInComponent:3];  //时
            //如果现在的年份(2017)大于pickerView上选择的年份(2016),pickerView显示当前年份(2017)
            if (self.nowYear>=[self.yearMuAry[row] integerValue])
            {
                [self.pickerView selectRow:self.nowYear-2016 inComponent:0 animated:YES];
                
                //如果现在的月份(4)大于pickerView上选择的月份(3),pickerView显示当前月份(4)
                if (self.nowMonth>=[self.monthAry[row1] integerValue])
                {
                    [pickerView  selectRow:self.nowMonth-1 inComponent:1 animated:YES];
                    
                    //如果现在的天数大于pickerView上选择的天数,pickerView显示当前天数
                    if (self.nowDay>=row2+1)
                    {
                        [pickerView  selectRow:self.nowDay-1 inComponent:2 animated:YES];
                        
                        //如果现在的时间大于pickerView上选择的时间,pickerView显示当前时间
                        NSInteger hour    =   row3/2;      //当前时间列在的小时时间
                        if (self.nowHour>=hour){
                            [pickerView  selectRow:self.nowHour*2 inComponent:3 animated:YES];
                            if (self.nowMinu<30) {
                                [pickerView  selectRow:self.nowHour*2+1 inComponent:3 animated:YES];
                            }else{
                                //                                [pickerView  selectRow:self.nowHour*2+2 inComponent:3 animated:YES];
                                [self    mimuFullIntoDay];
                            }
                        }
                    }
                }
            }
        }
            break;
        case 1:
        {
            NSInteger   row0    =   [pickerView selectedRowInComponent:0];  //年
            NSInteger   row1    =   row;
            NSInteger   row2    =   [pickerView selectedRowInComponent:2];  //天
            NSInteger   row3    =   [pickerView selectedRowInComponent:3];  //时
            //如果现在的年份(2017)大于pickerView上选择的年份(2016),pickerView显示当前年份(2017)
            if (self.nowYear>=[self.yearMuAry[row0] integerValue])
            {
                //                [self.pickerView selectRow:self.nowYear-2016 inComponent:0 animated:YES];
                
                //如果现在的月份(4)大于pickerView上选择的月份(3),pickerView显示当前月份(4)
                if (self.nowMonth>=[self.monthAry[row1] integerValue])
                {
                    [pickerView  selectRow:self.nowMonth-1 inComponent:1 animated:YES];
                    
                    //如果现在的天数大于pickerView上选择的天数,pickerView显示当前天数
                    if (self.nowDay>=row2+1)
                    {
                        [pickerView  selectRow:self.nowDay-1 inComponent:2 animated:YES];
                        
                        //如果现在的时间大于pickerView上选择的时间,pickerView显示当前时间
                        NSInteger hour    =   row3/2;      //当前时间列在的小时时间
                        if (self.nowHour>=hour){
                            [pickerView  selectRow:self.nowHour*2 inComponent:3 animated:YES];
                            if (self.nowMinu<30) {
                                [pickerView  selectRow:self.nowHour*2+1 inComponent:3 animated:YES];
                            }else{
                                //                                [pickerView  selectRow:self.nowHour*2+2 inComponent:3 animated:YES];
                                [self    mimuFullIntoDay];
                            }
                        }
                    }
                }
            }
#ifdef DEBUG
            DLog(@"滑动了0列");
#endif
        }
            break;
        case 2:
        {
            NSInteger   row0    =   [pickerView selectedRowInComponent:0];  //年
            NSInteger   row1    =   [pickerView selectedRowInComponent:1];  //月
            NSInteger   row2    =   row;  //天
            NSInteger   row3    =   [pickerView selectedRowInComponent:3];  //时
            //如果现在的年份(2017)大于pickerView上选择的年份(2016),pickerView显示当前年份(2017)
            if (self.nowYear>=[self.yearMuAry[row0] integerValue])
            {
                //                [self.pickerView selectRow:self.nowYear-2016 inComponent:0 animated:YES];
                
                //如果现在的月份(4)大于pickerView上选择的月份(3),pickerView显示当前月份(4)
                if (self.nowMonth>=[self.monthAry[row1] integerValue])
                {
                    //                    [pickerView  selectRow:self.nowMonth-1 inComponent:1 animated:YES];
                    
                    //如果现在的天数大于pickerView上选择的天数,pickerView显示当前天数
                    if (self.nowDay>=row2+1)
                    {
                        [pickerView  selectRow:self.nowDay-1 inComponent:2 animated:YES];
                        
                        //如果现在的时间大于pickerView上选择的时间,pickerView显示当前时间
                        NSInteger hour    =   row3/2;      //当前时间列在的小时时间
                        if (self.nowHour>=hour){
                            [pickerView  selectRow:self.nowHour*2 inComponent:3 animated:YES];
                            if (self.nowMinu<30) {
                                [pickerView  selectRow:self.nowHour*2+1 inComponent:3 animated:YES];
                            }else{
                                //                                [pickerView  selectRow:self.nowHour*2+2 inComponent:3 animated:YES];
                                [self    mimuFullIntoDay];
                            }
                        }
                    }
                }
            }

            DLog(@"滑动了2列");
            
        }
            break;
        case 3:
        {
            NSInteger   row0    =   [pickerView selectedRowInComponent:0];  //年
            NSInteger   row1    =   [pickerView selectedRowInComponent:1];  //月
            NSInteger   row2    =   [pickerView selectedRowInComponent:2];  //天
            NSInteger   row3    =   row;  //时
            
            //如果现在的年份(2017)大于pickerView上选择的年份(2016),pickerView显示当前年份(2017)
            if (self.nowYear>=[self.yearMuAry[row0] integerValue])
            {
                //                [self.pickerView selectRow:self.nowYear-2016 inComponent:0 animated:YES];
                
                //如果现在的月份(4)大于pickerView上选择的月份(3),pickerView显示当前月份(4)
                if (self.nowMonth>=[self.monthAry[row1] integerValue])
                {
                    //                    [pickerView  selectRow:self.nowMonth-1 inComponent:1 animated:YES];
                    
                    //如果现在的天数大于pickerView上选择的天数,pickerView显示当前天数
                    if (self.nowDay>=row2+1)
                    {
                        //                        [pickerView  selectRow:self.nowDay-1 inComponent:2 animated:YES];
                        
                        //如果现在的时间大于pickerView上选择的时间,pickerView显示当前时间
                        NSInteger hour    =   row3/2;      //当前时间列在的小时时间
                        if (self.nowHour>=hour){
                            [pickerView  selectRow:self.nowHour*2 inComponent:3 animated:YES];
                            if (self.nowMinu<30) {
                                [pickerView  selectRow:self.nowHour*2+1 inComponent:3 animated:YES];
                            }else{
                                //                                [pickerView  selectRow:self.nowHour*2+2 inComponent:3 animated:YES];
                                [self    mimuFullIntoDay];
                            }
                        }
                    }
                }
            }

            DLog(@"滑动了3列");
        }
            break;
        default:
            break;
    }
    [self    getSelectTimeStr];
    [pickerView  reloadComponent:1];
}

//数据源
- (void)sourceAry
{
    
    self.monthAry    =   [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12", nil];
    self.hourAry    =   [NSArray arrayWithObjects:@"00",@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23", nil];
    self.minuAry    =   [NSArray arrayWithObjects:@"00",@"30", nil];
    self.yearMuAry  =   [NSMutableArray array];
    for (int i=0; i<3; i++) {
        [self.yearMuAry  addObject:[NSString stringWithFormat:@"%ld",(long)self.nowYear+i]];
    }
}

//获得当前的时间,年,月,日,时,分
- (void)getNowTime
{
    NSDate *nowDate =   [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm"];
    
    NSString    * nowDateStr    =   [formatter stringFromDate:nowDate];

    DLog(@"%@",nowDateStr);

    
    
    NSArray * array   =   [nowDateStr componentsSeparatedByString:@"-"];
    
    self.nowYear    =   [array[0] integerValue];
    self.nowMonth   =   [array[1] integerValue];
    self.nowDay     =   [array[2] integerValue];
    self.nowHour    =   [array[3] integerValue];

    DLog(@"%ld",(long)self.nowHour);

    
    self.nowMinu    =   [array[4] integerValue];
    //    self.nowYear    =   2016;
    //    self.nowMonth   =   12;
    //    self.nowDay     =   31;
    //    self.nowHour    =   23;
    //    self.nowMinu    =   45;
    //
}

//计算当前年,当前月的天数
- (NSInteger)getDaysWithYearAndMonth
{
    NSInteger month =   [self.pickerView selectedRowInComponent:1]+1; //选择器的月数
    NSInteger year   =   [self.pickerView selectedRowInComponent:0]+2016; //选择器年的行数
    
    if (month==1||month==3||month==5||month==7||month==8||month==10||month==12) {
        return 31;
    }else if(month==4||month==6||month==9||month==11){
        return 30;
    }else if (((year%4==0)&&(year%100!=0))||(year%400==0)){
        return 29;
    }else{
        return 28;
    }
}

//把日期拼接到一起
- (void)getSelectTimeStr
{
    NSString    *yearStr    =   self.yearMuAry[[self.pickerView selectedRowInComponent:0] ];
    NSString    *monthStr   =   self.monthAry[[self.pickerView selectedRowInComponent:1]];
    NSString    *dayStr     =   [NSString stringWithFormat:@"%ld",(long)[self.pickerView selectedRowInComponent:2]+1];
    NSInteger   row3    =   [self.pickerView selectedRowInComponent:3];
    NSString    *minStr     =   [NSString stringWithFormat:@"%@:%@",self.hourAry[row3/2],self.minuAry[row3%2]];
    
    NSString    * str = [NSString stringWithFormat:@"%@-%@-%@ %@",yearStr,monthStr,dayStr,minStr];
    

    DLog(@"%@",str);

    
    self.chooseTimeStr   =   str;
}

//消失
- (void)dismissDatePicker:(UIButton *)butt
{
    
    
    NSString    *yearStr    =   self.yearMuAry[self.yearRow];
    NSString    *monthStr   =   self.monthAry[self.monthRow];
    NSString    *dayStr     =   [NSString stringWithFormat:@"%ld",(long)self.dayRow+1];
    NSString    *minStr     =   [NSString stringWithFormat:@"%@:%@",self.hourAry[self.hourRow/2],self.minuAry[self.hourRow%2]];
    
    NSString    * str = [NSString stringWithFormat:@"%@-%@-%@ %@",yearStr,monthStr,dayStr,minStr];
    
    NSString    * timeStr   =   (self.chooseTimeStr!=nil)?_chooseTimeStr:str;
    
    //代理的回调
    if ([self respondsToSelector:@selector(chooseTimePickerView:getUseTime:)]) {
        [self.delegate chooseTimePickerView:self getUseTime:timeStr];
    }
    
    //block的回调
    if (self.chooseTimeViewBlock) {
        self.chooseTimeViewBlock(timeStr);
    }
    
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.pickerViewCase.frame = CGRectMake(30*WFACTOR, kWinH, 260*WFACTOR, 160*WFACTOR);
        weakSelf.bgButton.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        [weakSelf.pickerViewCase removeFromSuperview];
        [weakSelf.bgButton removeFromSuperview];
        [weakSelf removeFromSuperview];
        
    }];
}

@end
